package cn.wolfcode.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.query.JsonResult;
import cn.wolfcode.service.IEmployeeService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created by Administrator on 2020/5/13.
 */
@Controller
@RequestMapping("/pwd")
public class PwdController {
    @Autowired
    private IEmployeeService employeeService;

    //修改密码
    @RequestMapping("/jump")
    public String update(){
        return "login/updatePwd";
    }

    @RequestMapping("/update")
    @ResponseBody
    public JsonResult updatePwd(String oldPassword,String newPassword){
        Employee employee = (Employee)SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        String password = employee.getPassword();
        Md5Hash oldmd5Hash = new Md5Hash(oldPassword,employee.getName());
        if (!(password.toString()
                .equals(oldmd5Hash.toString()))){
            return new JsonResult(false,"原密码不一致");
        }
        employeeService.updatePwd(employee.getName(),newPassword);
        return new JsonResult();

    }

    @RequestMapping("/resetPwd")
    public String resetPwd(Model model, Long id){
        Employee employee = employeeService.get(id);
        model.addAttribute("employee",employee);
        return "login/resetPwd";
    }

    @RequestMapping("/reset")
    @ResponseBody
    public JsonResult reset(String Password, Long id){
        if (Password!=null && Password.trim().length()>0){
            Employee employee = employeeService.get(id);
            employeeService.updatePwd(employee.getName(),Password);
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
            return new JsonResult();
        }

        return new JsonResult(false,"请输入需要重置的密码");
    }

}
